package com.itheima.config;

import com.itheima.security.HealthUserDetailServiceImpl;
import com.itheima.security.JWTAuthenticationFilter;
import com.itheima.security.JWTAuthorizationFilter;
import com.itheima.security.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 重写默认配置类  WebSecurityConfigurerAdapter
 * configure (AuthenticationManagerBuilder auth)   重写默认的用户认证信息 参照源码 注释编写
 * <p>
 * request.getParameter()    HttpxxxxWrapper   包装类   MvcWebConfigure  json null
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true) //  开启权限注解
@EnableConfigurationProperties(JwtProperties.class)
public class HealthWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    private HealthUserDetailServiceImpl healthUserDetailService;

    @Autowired
    private JwtProperties properties;  //  注入 jwt需要公钥和私钥 配置类

    /**
     * 重写用户认证信息
     *
     * @param auth
     * @throws Exception 密码加密 框架  PasswordEncoder  密码加密
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //  数据库认证和授权配置
        auth.userDetailsService(healthUserDetailService).passwordEncoder(createPasswordEncoder());
    }

    /**
     * PasswordEncoder  对密码进行加密
     *
     * @return
     */
    @Bean
    public PasswordEncoder createPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().
                disable().
                addFilter(new JWTAuthenticationFilter(super.authenticationManager(), properties))
                .addFilter(new JWTAuthorizationFilter(super.authenticationManager(), properties))
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS); // 禁用session
    }
}



